package com.lcn.core.service.aop;

import com.lcn.comm.domain.TxTransactionInfo;
import com.lcn.comm.service.aop.TransactionServerFactoryService;
import com.lcn.comm.service.aop.TransactionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>类说明</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @create: 上午10:32
 */
@Service
public class TransactionServerFactoryServiceImpl implements TransactionServerFactoryService {

    @Resource(name = "startTransactionService")
    private TransactionService startTransactionService;

    @Resource(name = "runningTransactionService")
    private TransactionService runningTransactionService;

    @Resource(name = "defaultTransactionService")
    private TransactionService defaultTransactionService;

    /**
     * 创建transactionService
     *
     * @param info
     * @return
     * @throws Throwable
     */
    public TransactionService createTransactionService(TxTransactionInfo info) {
        /*******************************分布式事务处理逻辑 开始**********************************/

        /** 分布式事务注解TxTransaction注解不为空，其他都为空时。表示分布式事务开始启动 **/
        if (info.getTxTransaction() != null && info.getTxTransactionLocal() == null && StringUtils.isEmpty(info.getGroupId())) {
            return startTransactionService;
        }

        /**分布式事务已经启动，业务进行中*/
        if (info.getTxTransactionLocal() != null || StringUtils.isNotEmpty(info.getGroupId())) {
            if (info.getTxTransactionLocal() != null) {//已经running进行中
                return defaultTransactionService;
            } else {//第一次进入running
                return runningTransactionService;
            }
        }


        /*******************************分布式事务处理逻辑 结束**********************************/
        return defaultTransactionService;
    }
}
